<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-6">数据统计</h1>
    
    <div v-if="loading" class="flex justify-center py-8">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>
    
    <div v-else>
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-gray-500 text-sm font-medium">总销售额</h3>
            <div class="p-2 rounded-full bg-blue-100">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
          </div>
          <div class="flex items-end">
            <span class="text-2xl font-bold">¥{{ formatNumber(statistics.totalSales) }}</span>
            <span class="text-sm text-gray-500 ml-2 mb-1">元</span>
          </div>
          <div class="mt-2 text-sm" :class="statistics.salesGrowth >= 0 ? 'text-green-500' : 'text-red-500'">
            <span v-if="statistics.salesGrowth >= 0">↑</span>
            <span v-else>↓</span>
            {{ Math.abs(statistics.salesGrowth) }}% 较上周
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-gray-500 text-sm font-medium">订单数量</h3>
            <div class="p-2 rounded-full bg-green-100">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
            </div>
          </div>
          <div class="flex items-end">
            <span class="text-2xl font-bold">{{ formatNumber(statistics.totalOrders) }}</span>
            <span class="text-sm text-gray-500 ml-2 mb-1">单</span>
          </div>
          <div class="mt-2 text-sm" :class="statistics.ordersGrowth >= 0 ? 'text-green-500' : 'text-red-500'">
            <span v-if="statistics.ordersGrowth >= 0">↑</span>
            <span v-else>↓</span>
            {{ Math.abs(statistics.ordersGrowth) }}% 较上周
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-gray-500 text-sm font-medium">用户数量</h3>
            <div class="p-2 rounded-full bg-purple-100">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
              </svg>
            </div>
          </div>
          <div class="flex items-end">
            <span class="text-2xl font-bold">{{ formatNumber(statistics.totalUsers) }}</span>
            <span class="text-sm text-gray-500 ml-2 mb-1">人</span>
          </div>
          <div class="mt-2 text-sm" :class="statistics.usersGrowth >= 0 ? 'text-green-500' : 'text-red-500'">
            <span v-if="statistics.usersGrowth >= 0">↑</span>
            <span v-else>↓</span>
            {{ Math.abs(statistics.usersGrowth) }}% 较上周
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-gray-500 text-sm font-medium">团购活动</h3>
            <div class="p-2 rounded-full bg-yellow-100">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" />
              </svg>
            </div>
          </div>
          <div class="flex items-end">
            <span class="text-2xl font-bold">{{ formatNumber(statistics.totalGroupBuys) }}</span>
            <span class="text-sm text-gray-500 ml-2 mb-1">个</span>
          </div>
          <div class="mt-2 text-sm" :class="statistics.groupBuysGrowth >= 0 ? 'text-green-500' : 'text-red-500'">
            <span v-if="statistics.groupBuysGrowth >= 0">↑</span>
            <span v-else>↓</span>
            {{ Math.abs(statistics.groupBuysGrowth) }}% 较上周
          </div>
        </div>
      </div>
      
      <!-- 销售趋势图 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-lg font-semibold">销售趋势</h2>
          <div class="flex space-x-2">
            <button 
              v-for="period in ['周', '月', '年']" 
              :key="period"
              @click="changeSalesPeriod(period)"
              :class="[
                'px-3 py-1 text-sm rounded-md',
                salesPeriod === period 
                  ? 'bg-primary text-white' 
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              ]"
            >
              {{ period }}
            </button>
          </div>
        </div>
        <div class="h-80">
          <!-- 这里可以使用图表库如 Chart.js 或 ECharts -->
          <div v-if="!salesChartData.length" class="h-full flex items-center justify-center text-gray-500">
            暂无销售数据
          </div>
          <div v-else class="h-full">
            <!-- 简单模拟图表 -->
            <div class="h-full flex items-end">
              <div 
                v-for="(item, index) in salesChartData" 
                :key="index"
                class="flex-1 mx-1 flex flex-col items-center"
              >
                <div 
                  class="w-full bg-blue-500 rounded-t-sm hover:bg-blue-600 transition-all cursor-pointer relative group"
                  :style="{ height: `${(item.value / maxSalesValue) * 100}%` }"
                >
                  <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 bg-gray-800 text-white text-xs py-1 px-2 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
                    ¥{{ formatNumber(item.value) }}
                  </div>
                </div>
                <div class="text-xs text-gray-500 mt-2">{{ item.label }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 热门商品和订单统计 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
        <!-- 热门商品 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-lg font-semibold mb-4">热门商品</h2>
          <div v-if="!statistics.popularProducts.length" class="py-8 text-center text-gray-500">
            暂无数据
          </div>
          <div v-else>
            <div v-for="(product, index) in statistics.popularProducts" :key="product.id" 
              class="flex items-center py-3" :class="{'border-b': index < statistics.popularProducts.length - 1}">
              <div class="flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full" :class="index < 3 ? 'bg-primary text-white' : 'bg-gray-100 text-gray-500'">
                {{ index + 1 }}
              </div>
              <div class="ml-4 flex-1">
                <div class="font-medium">{{ product.name }}</div>
                <div class="text-sm text-gray-500">销量: {{ product.sales }}件</div>
              </div>
              <div class="text-right">
                <div class="font-medium">¥{{ product.price }}</div>
                <div class="text-sm text-gray-500">{{ product.category }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 订单统计 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-lg font-semibold mb-4">订单统计</h2>
          <div class="grid grid-cols-2 gap-4">
            <div v-for="(item, status) in statistics.orderStatusCount" :key="status" 
              class="bg-gray-50 rounded-lg p-4 flex flex-col items-center justify-center">
              <div class="text-3xl font-bold mb-2" :class="getOrderStatusColor(status)">
                {{ item }}
              </div>
              <div class="text-sm text-gray-500">{{ getOrderStatusText(status) }}</div>
            </div>
          </div>
          
          <!-- 订单转化率 -->
          <div class="mt-6">
            <div class="flex justify-between mb-2">
              <span class="text-sm text-gray-500">订单转化率</span>
              <span class="text-sm font-medium">{{ statistics.orderConversionRate }}%</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2.5">
              <div class="bg-primary h-2.5 rounded-full" :style="{ width: `${statistics.orderConversionRate}%` }"></div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 用户分析 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
        <h2 class="text-lg font-semibold mb-6">用户分析</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
          <!-- 用户增长 -->
          <div>
            <h3 class="text-base font-medium mb-4">用户增长趋势</h3>
            <div class="h-60">
              <!-- 简单模拟图表 -->
              <div class="h-full flex items-end">
                <div 
                  v-for="(item, index) in userGrowthData" 
                  :key="index"
                  class="flex-1 mx-1 flex flex-col items-center"
                >
                  <div 
                    class="w-full bg-purple-500 rounded-t-sm hover:bg-purple-600 transition-all cursor-pointer relative group"
                    :style="{ height: `${(item.value / maxUserValue) * 100}%` }"
                  >
                    <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 bg-gray-800 text-white text-xs py-1 px-2 rounded opacity-0 group-hover:opacity-100 transition-opacity">
                      {{ item.value }}人
                    </div>
                  </div>
                  <div class="text-xs text-gray-500 mt-2">{{ item.label }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 用户分布 -->
          <div>
            <h3 class="text-base font-medium mb-4">用户地区分布</h3>
            <div v-if="!statistics.userRegions.length" class="py-8 text-center text-gray-500">
              暂无数据
            </div>
            <div v-else>
              <div v-for="(region, index) in statistics.userRegions" :key="region.name" 
                class="mb-3" :class="{'border-b pb-3': index < statistics.userRegions.length - 1}">
                <div class="flex justify-between mb-1">
                  <span>{{ region.name }}</span>
                  <span>{{ region.percentage }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div class="bg-purple-500 h-2 rounded-full" :style="{ width: `${region.percentage}%` }"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { computed, onMounted, ref } from 'vue'

export default {
  name: 'StatisticsView',
  setup() {
    const loading = ref(true)
    const statistics = ref({
      totalSales: 0,
      salesGrowth: 0,
      totalOrders: 0,
      ordersGrowth: 0,
      totalUsers: 0,
      usersGrowth: 0,
      totalGroupBuys: 0,
      groupBuysGrowth: 0,
      popularProducts: [],
      orderStatusCount: {},
      orderConversionRate: 0,
      userRegions: []
    })
    
    const salesPeriod = ref('周')
    const salesChartData = ref([])
    const userGrowthData = ref([])
    
    const maxSalesValue = computed(() => {
      if (!salesChartData.value.length) return 1
      return Math.max(...salesChartData.value.map(item => item.value)) || 1
    })
    
    const maxUserValue = computed(() => {
      if (!userGrowthData.value.length) return 1
      return Math.max(...userGrowthData.value.map(item => item.value)) || 1
    })
    
    const fetchStatistics = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/statistics/overview')
        if (response.data.code === 200) {
          statistics.value = response.data.data
          
          // 初始化销售趋势数据
          initSalesChartData()
          
          // 初始化用户增长数据
          initUserGrowthData()
        } else {
          console.error('获取统计数据失败:', response.data.message)
        }
      } catch (error) {
        console.error('获取统计数据出错:', error)
      } finally {
        loading.value = false
      }
    }
    
    const initSalesChartData = () => {
      // 模拟数据，实际应从API获取
      if (salesPeriod.value === '周') {
        salesChartData.value = [
          { label: '周一', value: 2500 },
          { label: '周二', value: 3800 },
          { label: '周三', value: 5000 },
          { label: '周四', value: 4200 },
          { label: '周五', value: 6300 },
          { label: '周六', value: 8500 },
          { label: '周日', value: 7200 }
        ]
      } else if (salesPeriod.value === '月') {
        salesChartData.value = Array.from({ length: 30 }, (_, i) => ({
          label: `${i + 1}日`,
          value: Math.floor(Math.random() * 10000) + 1000
        }))
      } else {
        salesChartData.value = [
          { label: '1月', value: 35000 },
          { label: '2月', value: 28000 },
          { label: '3月', value: 42000 },
          { label: '4月', value: 55000 },
          { label: '5月', value: 63000 },
          { label: '6月', value: 75000 },
          { label: '7月', value: 85000 },
          { label: '8月', value: 92000 },
          { label: '9月', value: 86000 },
          { label: '10月', value: 94000 },
          { label: '11月', value: 105000 },
          { label: '12月', value: 125000 }
        ]
      }
    }
    
    const initUserGrowthData = () => {
      // 模拟数据，实际应从API获取
      userGrowthData.value = [
        { label: '1月', value: 120 },
        { label: '2月', value: 150 },
        { label: '3月', value: 180 },
        { label: '4月', value: 210 },
        { label: '5月', value: 250 },
        { label: '6月', value: 280 }
      ]
    }
    
    const changeSalesPeriod = (period) => {
      salesPeriod.value = period
      initSalesChartData()
    }
    
    const formatNumber = (num) => {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }
    
    const getOrderStatusText = (status) => {
      const statusMap = {
        '0': '待支付',
        '1': '已支付',
        '2': '已完成',
        '3': '已取消',
        '4': '已退款'
      }
      return statusMap[status] || '未知状态'
    }
    
    const getOrderStatusColor = (status) => {
      const colorMap = {
        '0': 'text-yellow-500',
        '1': 'text-blue-500',
        '2': 'text-green-500',
        '3': 'text-gray-500',
        '4': 'text-red-500'
      }
      return colorMap[status] || 'text-gray-500'
    }
    
    onMounted(fetchStatistics)
    
    return {
      loading,
      statistics,
      salesPeriod,
      salesChartData,
      userGrowthData,
      maxSalesValue,
      maxUserValue,
      changeSalesPeriod,
      formatNumber,
      getOrderStatusText,
      getOrderStatusColor
    }
  }
}
</script> 